#encoding: utf-8
class User < ActiveRecord::Base
  attr_accessible :email, :name, :password, :password_confirmation

  #before_save{ email.downcase! }
  before_save { |user| user.email = email.downcase }
  before_save :create_remember_token
  
  validates :name, :presence=> true , :length=> { :maximum=> 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
  validates :email, :presence=> true, :format=> { :with=> VALID_EMAIL_REGEX },
    :uniqueness=> { :case_sensitive=> false }
  validates :password , :length => { :minimum=> 6 , :message=> "Senha muito curta"}
  validates :password_confirmation, :presence=> { :message=> "Você precisa confirmar sua senha"}

  after_validation { self.errors.messages.delete(:password_digest) }
  
  has_secure_password

  has_many :microposts , :dependent=> :destroy
  #na tabela de relationships o usuário seguidor não eh identificado
  #como user, logo o rails não pode inferi-lo, logo digo qual eh o atributo que estou referenciando
  has_many :relationships , :foreign_key=> "follower_id" , :dependent=> :destroy
  has_many :reverse_relationships, :foreign_key=> "followed_id", :class_name=> "Relationship", :dependent=> :destroy
  has_many :follower_users , :through=> :relationships , :source=> :follower
  has_many :followed_users , :through=> :relationships , :source=> :followed

  def feed
    Micropost.from_users_followed_by(self)
  end

  def following?(other_user)
    relationships.find_by_followed_id(other_user.id)
  end

  def follow!(other_user)
    relationships.create!(:followed_id=> other_user.id)
  end

  def unfollow!(other_user)
    relationships.find_by_followed_id(other_user.id).destroy
  end

  private
  def create_remember_token
    self.remember_token = SecureRandom.urlsafe_base64
  end
end
